-module(device_manager).
-include("definitions.hrl").

-export([readDeviceListFromFile/0]).

readDeviceListFromFile() ->
  case file:open(?INPUT, [read]) of
    {ok, IoDevice} -> readCycle(IoDevice, []);
    _ ->
      io:format("Error while reading device list"),
      %не умирать
      [{"Device1", 1}, {"Device2", 2}]
  end.

-spec readCycle/2 :: (file:io_device(), [{string(), integer()}]) -> [{string(), integer()}].
readCycle(IoDevice, List) ->
  case file:read_line(IoDevice) of
    {ok, Data} ->
      %io:format(Data),
      %{S, N} = parseDevice(Data),
      %io:format(S),
      readCycle(IoDevice, [parseDevice(Data) | List]);
    {error, Reason} ->
      io:format(Reason),
      lists:reverse(List);
    eof -> lists:reverse(List)
  end.

parseDevice(RawPair) ->
  [Name, RawId] = string:tokens(RawPair, ",\n\r"),
  {Id, _} = string:to_integer(tl(RawId)),
  {Name, Id}.